<template>
  <el-container class="layout">
    <el-aside width="30%">
    <el-alert
      v-if="!contacts || contacts.length === 0"
      type="info"
      :closable="false"
      center
      show-icon
      title="找不到最近联系人"></el-alert>
    <el-menu :default-active="contact ? contact.oppositeUsername : ''">
        <el-menu-item
          v-for="item of contacts"
          :key="item.oppositeUsername"
          :index="item.oppositeUsername"
          @click="onUserSelect(item)">
        <el-badge class="msg-badge" :value="item.count">
          <i :class="['el-icon-user-solid', item.online ? 'online' : 'offline']"></i>
        </el-badge>
        <span>{{item.nickname}}</span>
        </el-menu-item>
    </el-menu>
    </el-aside>
    <el-container>
    <el-main id="msgMain">
      <el-divider v-if="history && history.length > 0"><a @click="onMoreHistory">点击查看更多消息</a></el-divider>
      <template v-for="(item, index) of history">
        <div v-if="item.fromId === user.id" class="msg-title" style="float:right;" :key="'user' + index">
          <el-tag v-if="item.createTime" size="mini">{{ formatTime(item.createTime) }}</el-tag>&nbsp;
          <el-tag size="mini">{{ user.nickname }}</el-tag>
        </div>
        <div v-else class="msg-title" style="float:left;" :key="'user' + index">
          <el-tag size="mini">{{ contact.nickname }}</el-tag>
          &nbsp;<el-tag v-if="item.createTime" size="mini">{{ formatTime(item.createTime) }}</el-tag>
        </div>
        <div :key="'clear0' + index" style="clear:both"></div>
        <el-card
          :key="'msg' + index"
          shadow="hover"
          body-style="padding: 10px;"
          :class="['bubble', (item.fromId === user.id ? 'bubble-right' : 'bubble-left')]">
          {{ item.content }}
        </el-card>
        <div :key="'clear1' + index" style="clear:both"></div>
      </template>
    </el-main>
    <el-footer height="137px">
      <el-input
        type="textarea"
        placeholder="请输入要发送的消息"
        v-model="textarea"
        class="msg-input"
        resize="none"
        :rows="6"
        suffix-icon="el-icon-date">
      </el-input>
      <el-button class="msg-send" type="primary" :loading="sendDisable" @click="sendMessage">发送</el-button>
    </el-footer>
    </el-container>
  </el-container>
</template>
<script >
  import dayjs from 'dayjs';
  import { doVerifyUser, doGetUsername } from '@/apis/user';
  import { doSessionList, doSessionHistory, doSendMessage, doUserStatus } from '@/apis/chat.js';
  import ZZToast from '@/utils/toast';

  export default {
    name: 'Message',
    data() {
      return {
        contacts: [],
        user: undefined,
        contact: undefined,
        history: [],
        historyIndex: 1,
        textarea: '',
        sendDisable: false
      };
    },
    methods: {
      async scrollToBottom() {
        await this.$nextTick();
        const e = document.getElementById('msgMain');
        e.scrollTop = e.scrollHeight;
      },
      formatTime(str) {
        return dayjs(str).format('YYYY-MM-DD HH:mm:ss');
      },
      async onUserSelect(contact) {
        if (this.contact === contact) return;
        this.contact = contact;
        this.historyIndex = 1;
        const res = await doSessionHistory(this.user.username, this.contact.oppositeUsername, this.historyIndex);
        if (res.code !== 200) {
          ZZToast.warn(res.message);
        } else {
          this.history = res.data.reverse();
          this.scrollToBottom();
        }
      },
      async onMoreHistory() {
        const res = await doSessionHistory(this.user.username, this.contact.oppositeUsername, ++this.historyIndex);
        if (res.code !== 200) {
          ZZToast.warn(res.message);
        } else {
          this.history.unshift(...res.data.reverse());
        }
      },
      async sendMessage() {
        if (!this.contact) {
          ZZToast.warn('请先选择一位联系人');
          return;
        }
        if (!this.textarea) return;
        this.sendDisable = true;
        try {
          const res = await doSendMessage(this.user.username, this.contact.oppositeUsername, this.textarea);
          if (res.code !== 200) {
            ZZToast.warn(res.message);
          } else {
            this.history.push({
              fromId: this.user.id,
              fromUsername: this.user.username,
              toId: this.contact.oppositeId,
              createTime: this.formatTime(),
              content: this.textarea
            });
            this.textarea = '';
            this.scrollToBottom();
          }
        } finally {
          this.sendDisable = false;
        }
      },
      async setActive(contact) {
        for (const c of this.contacts) {
          if (c.oppositeId === contact.oppositeId) {
            await this.onUserSelect(c);
            this.contact = c;
            return;
          }
        }
        this.contacts.push(contact);
        await this.onUserSelect(contact);
        this.contact = contact;
      },
      async getUserStatus() {
        if (!this.contacts) return;
        const sl = await doSessionList(this.user, true);
        for (const item of this.contacts) {
          const res = await doUserStatus(item.oppositeUsername);
          item.online = res.data;
          for (const i of sl) {
            if (item.oppositeId !== i.oppositeId) continue;
            if (item.count === i.count) continue;
            item.count = i.count;
            if (item === this.contact && item.count > 0) {
              this.onUserSelect(this.contact);
            }
          }
        }
      }
    },
    async mounted() {
      const token = this.cache.fetchToken();
      if (!token) this.$router.replace('/');
      const ret = await doVerifyUser(token);
      if (!ret) this.$router.replace('/');
      this.user = this.cache.fetchUser();
      let res = await doSessionList(this.user);
      if (res.code !== 200) {
        ZZToast.warn(res.message);
        return;
      }
      this.contacts = res.data;
      // 获取每个用户的在线状态
      // debug
      // this.contacts.push({
      //   oppositeId: 14,
      //   oppositeUsername: '18086263199',
      //   nickname: '18086263199',
      //   icon: '发送者头像',
      //   oppositeType: '0',
      //   count: '消息数量',
      //   online: 1
      // });
      const val = this.$store.state.sendMsgMemberId;
      if (val) {
        console.log(val);
        res = await doGetUsername(val);
        if (res.code === 200) {
          this.setActive({
            oppositeId: val,
            oppositeUsername: res.data.username,
            nickname: res.data.nickname,
            online: res.data.onLineStatus
          });
        }
      }
      // setInterval(this.getUserStatus, 5000);
    }
  };
</script>
<style lang="scss" type="text/scss" scoped>
.layout {
  height: 100%;
}
.el-aside {
  background-color: #eee;
  text-align: left;
}
.el-main {
  padding: 0 10px 0 10px;
}
.el-footer {
  padding: 0;
  div {
    display: inline-block;
  }
}
.offline {
  color: gray !important;
}
.online {
  color: lightgreen !important;
}
.msg-input {
  width: 80%;
}
.msg-send {
  margin-left: 3px;
  width: 19%;
  height: 100%;
}
.bubble {
  width: fit-content;
  word-wrap:break-word;
  max-width: 90%;
  margin-bottom: 10px;
}
.bubble-left {
  background-color: #ffe;
  float: left;
}
.bubble-right {
  background-color: #ced;
  float: right;
}
.msg-title {
  font-size: 13px;
  color: gray;
  margin-bottom: 5px;
}
</style>
<style lang="scss" type="text/scss">
.msg-badge {
  .el-badge__content {
    top: 12px !important;
  }
}
</style>
